package com.luna.cloudworm.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.luna.cloudworm.product.dao.SkuInfoDao;
import com.luna.cloudworm.product.entity.SkuImagesEntity;
import com.luna.cloudworm.product.entity.SkuInfoEntity;
import com.luna.cloudworm.product.entity.SpuInfoDescEntity;
import com.luna.cloudworm.product.service.*;
import com.luna.cloudworm.product.vo.SkuItemSaleAttrVo;
import com.luna.cloudworm.product.vo.SkuItemVo;
import com.luna.cloudworm.product.vo.SpuItemAttrGroupVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        /**
         * key:
         * catelogId: 0
         * brandId: 0
         * min: 0
         * max: 0
         */
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key) && !"0".equalsIgnoreCase(key)) {
            wrapper.and(w -> w.eq("sku_id", key).or().like("sku_name", key));
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.and(w -> w.eq("catalog_id", catelogId));
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.and(w -> w.eq("brand_id", brandId));
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min) && !"0".equalsIgnoreCase(min)) {
            wrapper.and(w -> w.ge("price", min));
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max) && !"0".equalsIgnoreCase(max)) {
            wrapper.and(w -> w.le("price", max));
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 根据spuId查询所有sku信息
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {

        return this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }


    @Override
    @Transactional
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo item = new SkuItemVo();
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            // 1、当前sku的基本信息获取 pms_sku_info
            SkuInfoEntity info = getById(skuId);
            item.setInfo(info);
            return info;
        }, threadPoolExecutor);
        // 这三个是并行的，但是先等到infoFuture 运行完成之后
        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            // 3、获取spu的销售属性组合 pms_sku_info
            List<SkuItemSaleAttrVo> saleAttr = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            item.setSaleAttr(saleAttr);

        }, threadPoolExecutor);
        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            // 4、获取spu的介绍  pms_spu_info_desc
            SpuInfoDescEntity desp = spuInfoDescService.getById(res.getSpuId());
            item.setDesp(desp);

        }, threadPoolExecutor);

        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            // 5、获取spu的规格参数信息。获取当前商品的所有属性分组以及属性值
            List<SpuItemAttrGroupVo> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            item.setGroupAttrs(groupAttrs);

        }, threadPoolExecutor);


        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            // 2、获取sku的图片信息 pms_sku_images
            List<SkuImagesEntity> images = skuImagesService.getImagesBySkuIid(skuId);
            item.setImages(images);
        }, threadPoolExecutor);

        CompletableFuture<Void> secKillFuture = CompletableFuture.runAsync(() -> {
            // 3、查看当前sku是否参与秒杀优惠
            /*R r = seckillFeignService.getSkukillInfo(skuId);
            if (r.getCode() == 0) {
                SeckillInfoVo seckillInfoVo = r.getData(new TypeReference<SeckillInfoVo>() {
                });
                item.setSeckillInfoVo(seckillInfoVo);

            }*/
        }, threadPoolExecutor);
        // 等待所有任务都完成,infoFuture 可以不写，因为saleAttrFuture 都完成了infoFuture肯定完成了
        CompletableFuture.allOf(saleAttrFuture, descFuture, baseAttrFuture, imageFuture, secKillFuture).get();

        return item;
    }
}